﻿using HtmlAgilityPack;
using MusicExplorer.Repository.Internals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Fizzler.Systems.HtmlAgilityPack;
using System.Net;
using Newtonsoft.Json.Linq;

namespace MusicExplorer.Repository.SearchEngine
{
    public sealed class BingImageSearchEngine
    {
        private const string m_url_images_search =
            @"http://www.bing.com/images/search?q={0}&qft=+filterui:imagesize-medium";

        private readonly IDownloader m_downloader;

        public BingImageSearchEngine(IDownloader downloader)
        {
            m_downloader = downloader;
        }

        public async Task<List<string>> SearchImagesAsync(string terms, CancellationToken token)
        {
            var source = await m_downloader.GetOnlineSourceAsync(string.Format(m_url_images_search, terms), token);

            var document = new HtmlDocument();
            document.LoadHtml(source);
            var page = document.DocumentNode;

            var images = new List<string>();

            var imageNodes = page.QuerySelectorAll(".dg_u");
            foreach(var image in imageNodes)
            {
                var json = JObject.Parse(WebUtility.HtmlDecode(image.ChildNodes.First().Attributes["m"].Value));
                images.Add((string)json["imgurl"]);
            }

            return images;
        }
    }
}
